﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _80X_CG_Frame.Workers
{
    /// <summary>
    /// 新线程基类,基于Task
    /// </summary>
    public class WorkerBase
    {
        /// <summary>
        /// 线程对象
        /// </summary>
        protected Task task;
        /// <summary>
        /// 线程循环标志
        /// </summary>
        protected bool loop;
        /// <summary>
        /// 线程取消操作通知源
        /// </summary>
        protected CancellationTokenSource cts;
        /// <summary>
        /// 等待超时时间
        /// </summary>
        protected int wait_ms;

        public WorkerBase()
        {
            loop = false;
            wait_ms = 1000;
        }

        /// <summary>
        /// 线程执行方法
        /// </summary>
        protected virtual void Run()
        {
            //继承并将线程循环方法置于此
        }

        /// <summary>
        /// 启动线程
        /// </summary>
        public void Start()
        {
            if (loop)
                Cancel();
            loop = true;
            cts = new CancellationTokenSource();
            task = new Task(Run, cts.Token);
            task.Start();
        }

        /// <summary>
        /// 退出线程
        /// </summary>
        public void Cancel()
        {
            loop = false;
            if (cts == null)
            {
                //什么都不做
            }
            else if (!cts.IsCancellationRequested)
            {
                try
                {
                    task.Wait(wait_ms);
                    cts.Cancel();
                    task.Dispose();
                }
                catch (InvalidOperationException e)
                {
                    task.Wait();
                    System.Console.WriteLine(e.ToString());
                }
                finally
                {
                    cts.Dispose();
                }
            }
        }

        public async Task CancelAsync()
        {
            await Task.Run(() =>
            {
                Cancel();
            });
        }

        public TaskStatus Status()
        {
            return task.Status;
        }

        public bool IsRunning()
        {
            if (task == null)
                return false;
            if (task.Status == TaskStatus.Running)
                return true;
            return false;
        }
    }
}
